// stores/translation.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
    apiTranslateText,
    apiGetSupportedLanguages,
    apiTranslateArticle,
    apiBatchTranslateArticles,
    apiGetArticleTranslations
} from '@/api/translation'

export const useTranslationStore = defineStore('translation', () => {
    // 状态
    const supportedLanguages = ref({})
    const loading = ref(false)
    const translations = ref([])

    // 获取支持的语言列表
    const fetchSupportedLanguages = async () => {
        loading.value = true
        try {
            const response = await apiGetSupportedLanguages()
            supportedLanguages.value = response
            return response
        } catch (error) {
            ElMessage.error(error.message || '获取语言列表失败')
        } finally {
            loading.value = false
        }
    }

    // 翻译文本
    const translateText = async (text, targetLanguage) => {
        loading.value = true
        try {
            const response = await apiTranslateText({ text, targetLanguage })
            return response
        } catch (error) {
            ElMessage.error(error.message || '翻译失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 翻译文章
    const translateArticle = async (id, targetLanguage) => {
        loading.value = true
        try {
            const response = await apiTranslateArticle({ id, targetLanguage })
            return response
        } catch (error) {
            ElMessage.error(error.message || '文章翻译失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 批量翻译文章
    const batchTranslateArticles = async (articleIds, targetLanguage, updateOriginal) => {
        loading.value = true
        try {
            const response = await apiBatchTranslateArticles({
                articleIds,
                targetLanguage,
                updateOriginal
            })
            return response
        } catch (error) {
            ElMessage.error(error.message || '批量翻译失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    // 获取文章翻译版本
    const getArticleTranslations = async (id) => {
        loading.value = true
        try {
            const response = await apiGetArticleTranslations(id)
            translations.value = response
            return response
        } catch (error) {
            ElMessage.error(error.message || '获取翻译版本失败')
            throw error
        } finally {
            loading.value = false
        }
    }

    return {
        supportedLanguages,
        loading,
        translations,
        fetchSupportedLanguages,
        translateText,
        translateArticle,
        batchTranslateArticles,
        getArticleTranslations
    }
})